import 'package:flutter/material.dart';
import '../service/service_method.dart';
import 'package:flutter_swiper/flutter_swiper.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:url_launcher/url_launcher.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import '../routers/application.dart';

class Homepage extends StatefulWidget {
  @override
  _HomepageState createState() => _HomepageState();
}

class _HomepageState extends State<Homepage>
    with AutomaticKeepAliveClientMixin {
  int page = 1;
  List<Map> hotGoodList = [];
  @override
  bool get wantKeepAlive => true;

  @override
  void initState() {
    super.initState();
    print('1111111111111111111111111');
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text('工流界'),
        ),
        body: FutureBuilder(
            future: Future.wait([
              DioUtil.request('getHomeData'),
              DioUtil.request('getCategoryData'),
              DioUtil.request('getHomeDatap'),
              
            ]),
            builder: (context, snapshot) {
              print(snapshot);
              if (snapshot.hasData) {
                // var data = json.decode(snapshot.data.toString());
                List<Map> swiper =
                    (snapshot.data[0]['data'] as List).cast();
                    
                List<Map> navData = (snapshot.data[1]['data'] as List).cast();
                String phoneimg =
                    (snapshot.data[2]['data']['manager']);
                int phone = (snapshot.data[2]['data']['phone']);
                // print(recimmendList);
                // print(shangData);
                return EasyRefresh(
                  footer: ClassicalFooter(
                    bgColor: Colors.red,
                    textColor: Colors.white,
                    noMoreText: '',
                    infoText: '加载中',
                    loadedText: '上拉加载更多',
                  ),
                  child: ListView(
                    children: <Widget>[
                      SwiperDiy(
                        swiperData: swiper,
                      ),
                      TopNav(navData: navData),
                      Callup(phone: phone, phoneimg: phoneimg),
                      EndLists(),
                      _hotGoods(),
                    ],
                  ),
                  onLoad: () async {
                    await Future.delayed(Duration(seconds: 1), () {
                      print('开始加载更多.................');
                      var formPage = {'page': page};
                      DioUtil.request('getDirectGoodData', formData: formPage)
                          .then((val) {
                        var data = val['data'];
                        print(data);
                        print('首页商品');
                        List<Map> newGoodsList = (data as List).cast();
                        
                        setState(() {
                          hotGoodList.addAll(newGoodsList);
                          page++;
                        });
                      });
                    });
                  },
                );
              } else {
                return Center(
                  child: Text('加载中'),
                );
              }
            }));
  }

  Widget _wrapList() {
    if (hotGoodList.length != 0) {
      List<Widget> listWidget = hotGoodList.map((val) {
        return InkWell(
          onTap: () {
            Application.router
                .navigateTo(context, "detail?id=${val['id']}");
            print('你点击了商品ID${val['id']}');
            print('你点击了商品${val["title"]}');
          },
          child: Container(
            width: ScreenUtil().setWidth(372),
            color: Colors.grey,
            padding: EdgeInsets.all(5.0),
            margin: EdgeInsets.only(bottom: 3.0),
            child: Column(
              children: <Widget>[
                Image.network(
                  val['image'],
                  width: ScreenUtil().setWidth(370),
                ),
                Text(
                  val['title'],
                  maxLines: 1,
                  overflow: TextOverflow.ellipsis,
                  style: TextStyle(
                      color: Colors.pink, fontSize: ScreenUtil().setSp(26)),
                ),
                Row(
                  children: <Widget>[
                    Text("￥${val['price_text']}"),
                    Text(
                      "￥${val['price']}",
                      style: TextStyle(
                          color: Colors.black26,
                          decoration: TextDecoration.lineThrough),
                    )
                  ],
                )
              ],
            ),
          ),
        );
      }).toList();
      return Wrap(spacing: 2, children: listWidget);
    } else {
      return Text('没有数据');
    }
  }

  Widget _hotGoods() {
    return Container(
      child: Column(
        children: <Widget>[_wrapList()],
      ),
    );
  }
}

//首页轮播图
class SwiperDiy extends StatelessWidget {
  final List swiperData;
  SwiperDiy({this.swiperData});
  @override
  Widget build(BuildContext context) {
    return Container(
      height: ScreenUtil().setHeight(350),
      width: ScreenUtil().setWidth(750),
      child: Swiper(
        itemBuilder: (BuildContext context, int index) {
          return Image.network("${swiperData[index]['app_image']}");
        },
        itemCount: swiperData.length,
        pagination: SwiperPagination(),
        autoplay: true,
      ),
    );
  }
}

//宫格菜单
class TopNav extends StatelessWidget {
  final List navData;
  TopNav({Key key, this.navData}) : super(key: key);
  Widget _gridViewUi(BuildContext context, item) {
    return Container(
      child: InkWell(
        onTap: () {
          print('点击了导航');
        },
        child: Column(
          children: <Widget>[
            Image.network(
              item['icon_img'],
              width: ScreenUtil().setWidth(90.0),
              height: ScreenUtil().setHeight(80.0),
            ),
            Text(
              item['cate_name'],
            ),
          ],
        ),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      height: ScreenUtil().setHeight(320.0),
      padding: EdgeInsets.all(3.0),
      child: GridView.count(
        crossAxisCount: 4,
        childAspectRatio: 1.3 / 1,
        physics: NeverScrollableScrollPhysics(),
        padding: EdgeInsets.all(5.0),
        // physics: NeverScrollableScrollPhysics(),
        children: navData.map((item) {
          return _gridViewUi(context, item);
        }).toList(),
      ),
    );
  }
}

// 拨打电话
class Callup extends StatelessWidget {
  final String phoneimg;
  final int phone;
  Callup({Key key, this.phoneimg, this.phone}) : super(key: key);
  @override
  Widget build(BuildContext context) {
    return Container(
      height: 100.0,
      child: InkWell(
        onTap: _getCallup,
        child: Image.network(phoneimg, width: double.infinity),
      ),
    );
  }

  void _getCallup() async {
    String url = 'tel:' + '$phone';
    print(url);
    if (await canLaunch(url)) {
      await launch(url);
    } else {
      throw 'url错误';
    }
  }
}

//火爆商品
class EndLists extends StatefulWidget {
  @override
  _EndListsState createState() => _EndListsState();
}

class _EndListsState extends State<EndLists> {
  List<Map> formList = [];
  void _getList() {
    DioUtil.request('getHotGood').then((val) {
      List<Map> data = (val['data'] as List).cast();
      setState(() {
        formList = data;
      });
      // print(formList);
    });
    print('开始获取火爆商品数据啦');
  }

  @override
  void initState() {
    super.initState();
    _getList();
  }

  Widget buildGrid() {
    List<Widget> tiles = [];
    Widget content;
    for (var item in formList) {
      Widget _titleWudget() {
        return Container(
          alignment: Alignment.centerLeft,
          padding: EdgeInsets.fromLTRB(10.0, 2.0, 0, 5.0),
          decoration: BoxDecoration(
              color: Colors.grey,
              border: Border(
                  bottom: BorderSide(width: 1.0, color: Colors.black12))),
          child:
              Text('${item['cateName']}', style: TextStyle(color: Colors.pink)),
        );
      }

      Widget _items() {
        final itmes = item['goods'];
        return Container(
          height: ScreenUtil().setHeight(360),
          child: ListView.builder(
              scrollDirection: Axis.horizontal,
              itemCount: itmes.length,
              physics: BouncingScrollPhysics(),
              itemBuilder: (context, index) {
                return Container(
                  margin: EdgeInsets.only(right: 10),
                  width: ScreenUtil().setWidth(250),
                  decoration: BoxDecoration(
                      color: Colors.white,
                      border:Border.all(
                        width:1,color: Colors.black12
                      ),
                      borderRadius:  BorderRadius.all(Radius.elliptical(10, 10)), 
                  ),
                  child: InkWell(
                    onTap: () {
                      Application.router.navigateTo(
                          context, "detail?id=${itmes[index]['goods_id']}");
                      // print('点击了商品${itmes[index]}');
                    },
                    child: Column(
                      children: <Widget>[
                        Image.network(
                          '${itmes[index]['cover_img']}',
                          height: ScreenUtil().setHeight(250),
                        ),
                        Text(
                          '￥${itmes[index]['goods_name']}',
                          overflow: TextOverflow.ellipsis,
                        ),
                        Text(
                          '￥${itmes[index]['price']}',
                          style: TextStyle(
                              decoration: TextDecoration.lineThrough,
                              color: Colors.grey),
                        ),
                      ],
                    ),
                  ),
                );
              }),
        );
      }

      tiles.add(InkWell(
        child: Container(
          child: Column(
            children: <Widget>[_titleWudget(), _items()],
          ),
        ),
      ));
    }

    content = new Column(
      children: tiles,
    );
    return content;
  }

  Widget build(BuildContext context) {
    return Container(
        // height: ScreenUtil().setHeight(1000),
        width: ScreenUtil().setWidth(750),
        margin: EdgeInsets.only(top: 10.0),
        child: Column(
          children: <Widget>[buildGrid()],
        ));
  }
}

//商品推荐模块
// class Recimmend extends StatelessWidget {
//   final List recimmendList;
//   Recimmend({Key key, this.recimmendList}) : super(key: key);
//   Widget _titleWudget() {
//     return Container(
//       alignment: Alignment.centerLeft,
//       padding: EdgeInsets.fromLTRB(10.0, 2.0, 0, 5.0),
//       decoration: BoxDecoration(
//           color: Colors.grey,
//           border:
//               Border(bottom: BorderSide(width: 1.0, color: Colors.black12))),
//       child: Text('商品推荐', style: TextStyle(color: Colors.pink)),
//     );
//   }

// Widget _item(index) {
//   return InkWell(
//     onTap: () {
//       print('你点击了商品推荐');
//     },
//     child: Container(
//       height: ScreenUtil().setHeight(330),
//       width: ScreenUtil().setWidth(250),
//       padding: EdgeInsets.all(8.0),
//       decoration: BoxDecoration(
//           color: Colors.white,
//           border: Border(
//               left: BorderSide(width: 1, color: Colors.black12),
//               bottom: BorderSide(width: 1, color: Colors.black12))),
//       child: Column(
//         children: <Widget>[
//           Image.network(recimmendList[index]['cover_img']),
//           Text(
//             '￥${recimmendList[index]['goods_name']}',
//             overflow: TextOverflow.ellipsis,
//           ),
//           Text(
//             '￥${recimmendList[index]['price']}',
//             style: TextStyle(
//                 decoration: TextDecoration.lineThrough, color: Colors.grey),
//           ),
//         ],
//       ),
//     ),
//   );
// }

//   Widget _recommedList() {
//     return Container(
//       height: ScreenUtil().setHeight(330),
//       child: ListView.builder(
//           scrollDirection: Axis.horizontal,
//           itemCount: recimmendList.length,
//           physics: BouncingScrollPhysics(),
//           itemBuilder: (context, index) {
//             return _item(index);
//           }),
//     );
//   }

//   @override
//   Widget build(BuildContext context) {
//     return Container(
//       height: ScreenUtil().setHeight(400),
//       margin: EdgeInsets.only(top: 10.0),
//       child: Column(
//         children: <Widget>[_titleWudget(), _recommedList()],
//       ),
//     );
//   }
// }
